var express = require('express');
var router = express.Router();
var http = require('http');
var async = require('async');
var MongoClient = require('mongodb').MongoClient;
var DB_CONN_STR = "mongodb://localhost:27017/vue";

/* 跨域問題*/
router.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

router.get('/login', function(req, res, next) {


    var username = req.query.username;
    var pwd = req.query.pwd;
    var sex = req.query.sex;

    MongoClient.connect(DB_CONN_STR, function(err, db) {
        if (err) {
            alert(err);
        } else {
            var coll = db.collection('users');
            var data = {
                code: 1,
                meg: "登录成功"

            }
            coll.find({ name: username }).count(function(err, num) {
                if (num > 0) {

                    coll.find({ name: username, pwd: pwd }).count(function(err, num) {

                        if (num > 0) {
                            res.send(data);

                        } else {
                            data.code = -1;
                            data.meg = '用户名和密码不一致';
                            res.send(data);

                        }
                        db.close();
                    })
                } else {
                    coll.insertOne({ name: username, pwd: pwd }, function(err, result) {
                        if (err) {
                            data.code = -2;
                            data.meg = '注册失败';
                            res.send(data);
                        } else {
                            res.send(data);
                        }
                        db.close();
                    })
                }
            })

            // coll.find().toArray(function(err, arr) {
            //     res.send(arr);
            // })
        }

    })

})

module.exports = router;